package org.ning.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.ning.http.TimeUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/7/5 14:17
 */
@Data
public class TagResult {

    private int currentPage;
    private String library;
    private String nextUrl ;
    private List<Tag>  tagList;
    private int total;

    public int getTotalPage(){
        if(tagList.size() == 0)
            return 0;
        return total / tagList.size() + (total % tagList.size()>0? 0:1) ;
    }

    public static TagResult parseFromJson(JSONObject jsonObject, String library){
        try{
            TagResult result = new TagResult();
            result.setTotal(jsonObject.getInteger("count"));
            String next = jsonObject.getString("next");
            result.setNextUrl(next);
            JSONArray tags = jsonObject.getJSONArray("results");
            List<Tag> tagList = new ArrayList<>();
            tags.forEach(item->{
                JSONObject object = (JSONObject)item;
                Tag tag = new Tag();
                String tagName = object.getString("name");
                String pullCommand = "docker pull "+library + ":"+tagName;
                String dateStr = object.getString("last_updated");
                TimeUtils.parseTime(dateStr, tag);
                tag.setName(tagName);
                tag.setPullCommand(pullCommand);
                tagList.add(tag);
            });
            result.setTagList(tagList);
            return result;
        }catch (NullPointerException e){
            e.printStackTrace();
            throw new RuntimeException("解析异常");
        }


    }
}
